package com.boat.starter.ruoyi.client;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

import com.boat.starter.ruoyi.config.props.AuthProperties;
import com.boat.starter.ruoyi.model.LoginUser;

import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.util.Pool;

/**
 * redis客户端
 * 
 * @author 周江
 *
 */
@Slf4j
public class RedisClient {
	private Pool<Jedis> jedisPool;

	private AuthProperties authProperties;

	public RedisClient(AuthProperties authProperties) {
		this.authProperties = authProperties;
	}

	public void init() {
		GenericObjectPoolConfig config = new GenericObjectPoolConfig();
		config.setMinIdle(0);
		config.setMaxIdle(16);
		config.setMaxTotal(16);

		jedisPool = new JedisPool(config, authProperties.getRuoyi().getRedis().getHost(),
				authProperties.getRuoyi().getRedis().getPort(), authProperties.getRuoyi().getRedis().getTimeout(),
				authProperties.getRuoyi().getRedis().getPassword(), authProperties.getRuoyi().getRedis().getDatabase());
		log.info("初始化RedisClient完成");
	}

	/**
	 * 获得缓存的基本对象。
	 *
	 * @param key 缓存键值
	 * @return 缓存键值对应的数据
	 */
	public LoginUser getLoginUser(final String tokenKey) {
		try (Jedis client = jedisPool.getResource()) {
			String json = client.get(tokenKey);
			if (null != json) {
				LoginUser loginUser = new LoginUser();
				loginUser = com.alibaba.fastjson2.JSONObject.parseObject(json, LoginUser.class);
				return loginUser;
			}
			return null;
		}
	}

}
